﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using System.Diagnostics;
using AForge.Video.FFMPEG;
using System.Drawing.Imaging;
using System.IO;

namespace VideoCut
{
    public partial class Form1 : Form
    {
        private Stopwatch stopWatch = null;

        private String savePath;

        private int width;
        private int height;
        private int index;

        private Bitmap image;

        // 保存的图片地址列表
        private List<String> strImgList;

        public Form1()
        {
            InitializeComponent();
            listView.LargeImageList = imgList;
            savePath = System.Environment.CurrentDirectory + "\\picture";
            txtOutPath.Text = savePath;

            if (! Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            strImgList = new List<String>();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }


        // Open video source
        private void OpenVideoSource(IVideoSource source)
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // stop current video source
            CloseCurrentVideoSource();

            // start new video source
            videoSourcePlayer.VideoSource = source;
            videoSourcePlayer.Start();

            // reset stop watch
            stopWatch = null;

            // start timer
            timer.Start();

            this.Cursor = Cursors.Default;
        }

        // Close video source if it is running
        private void CloseCurrentVideoSource()
        {
            if (videoSourcePlayer.VideoSource != null)
            {
                videoSourcePlayer.SignalToStop();

                // wait ~ 3 seconds
                for (int i = 0; i < 30; i++)
                {
                    if (!videoSourcePlayer.IsRunning)
                        break;
                    System.Threading.Thread.Sleep(100);
                }

                if (videoSourcePlayer.IsRunning)
                {
                    videoSourcePlayer.Stop();
                }

                videoSourcePlayer.VideoSource = null;
            }
        }

        private void stopVideo()
        {
            // 首先需要暂停
            if (videoSourcePlayer.VideoSource != null && videoSourcePlayer.IsRunning)
            {
                videoSourcePlayer.Stop();
                timer.Stop();
            }
        }

        private void startVideo()
        {
            // 播放视频
            if (videoSourcePlayer.VideoSource != null)
            {
                videoSourcePlayer.Start();
                System.Threading.Thread.Sleep(100);
                timer.Start();
            }
        }

        /************************************************************************/
        /* 设置保存图片的路径                                                                     */
        /************************************************************************/
        private void setSavePath()
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK || folderBrowserDialog.ShowDialog() == DialogResult.Yes)
            {
                savePath = folderBrowserDialog.SelectedPath; //获得文件路径 
                txtOutPath.Text = savePath;
            }
        }

        /************************************************************************/
        /* 保存图片                                                                     */
        /************************************************************************/
        private void saveImage(ref Bitmap image)
        {
            String name = savePath + "\\" + getImageName();

            // 保存图片到本地
            image.Save(name, System.Drawing.Imaging.ImageFormat.Jpeg);
            strImgList.Add(name);

            // 显示图片到panel
            imgList.Images.Add(image);
            listView.Items.Add("帧"+(index+1));
            listView.Items[index].ImageIndex = index;
            index = index + 1;

            listView.Update();
        }

        /************************************************************************/
        /* 随机获取图片名                                                                     */
        /************************************************************************/
        private String getImageName()
        {
            return DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + index + ".jpg";
        }

        private void btnShot_Click(object sender, EventArgs e)
        {
            if (savePath.Equals(""))
            {
                btnSavePath_Click(sender, e);
            }
           
            // 获取当前图像
            image = videoSourcePlayer.GetCurrentVideoFrame();
            saveImage(ref image);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            String fileName;

            saveFileDialog.FileName = savePath + "\\1.mp4";

            if (saveFileDialog.ShowDialog() == DialogResult.OK || saveFileDialog.ShowDialog() == DialogResult.Yes)
            {
                fileName = saveFileDialog.FileName; //获得文件路径 

                if (strImgList.Count <= 0)
                {
                    return;
                }

                int i = 0, j;

                width = -1;

                progressBar.Maximum = strImgList.Count;
                progressBar.Visible = true;

                VideoFileWriter writer = new VideoFileWriter();

                for (i = 0; i < strImgList.Count; i++)
                {
                    Bitmap img = new Bitmap(Image.FromFile(strImgList[i]));
                    if (width == -1)
                    {
                        width = image.Width;
                        height = image.Height;

                        // 打开输出文件
                        writer.Open(fileName, width, height, 25, VideoCodec.MPEG4);
                    }

                    progressBar.Value = i+1;

                    // 25 为1秒
                    for (j = 0; j < 25; j++)
                    {
                        // 保存到writer
                        writer.WriteVideoFrame(img);
                    }
                }
                writer.Close();
                progressBar.Visible = false;

                // 写完了之后判断是否播放
                DialogResult r1 = MessageBox.Show("是否播放合成的视频？", "播放",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (r1 == DialogResult.Yes)
                {
                    playVideo(fileName);
                }
            }
        }

        private void playVideo(String fileName)
        {
            // 打开视频之前先关闭
            CloseCurrentVideoSource();

            // create video source
            VideoFileSource fileSource = new VideoFileSource(fileName);

            // open it
            OpenVideoSource(fileSource);

            // 初始化参数
            width = -1;
            height = -1;
            index = 0;
            imgList.Images.Clear();
            strImgList.Clear();
            listView.Items.Clear();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            // 打开视频
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                playVideo(openFileDialog.FileName);
            }
        }

        private void btnSavePath_Click(object sender, EventArgs e)
        {
            stopVideo();
            setSavePath();
            startVideo();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseCurrentVideoSource();
        }

    }
}
